package com.example.xksys.service.utils;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MyUtils {

	public String getRandomCode()
	{
		return ""+Math.floor(Math.random()*10000);
	}
	public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, String html) throws MessagingException, IOException
	{
		//1.创建邮件对象
		MimeMessage message=new MimeMessage(session);
		//2.From 发件人
		message.setFrom(new InternetAddress(sendMail,"发件人名称","UTF-8"));
		//3.To	发件人
		message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail,"张三","UTF-8"));
		//4.Subject 邮件主题
		message.setSubject("邮箱验证","UTF-8");
		//5.Content:邮件正文(可以用Html标签)
		message.setContent(html,"text/html;charset=UTF-8");
		//6.设置发送时间
		message.setSentDate(new Date());
		//7.保存设置
		message.saveChanges();
		//8.将邮箱保存到本地
		String fname="E://Mail//"+UUID.randomUUID()+".eml";
		File f=new File(fname);
		if(!f.exists()) {
			f.createNewFile();
		}
		OutputStream out=new FileOutputStream(f);
		message.writeTo(out);
		out.flush();
		out.close();
		return message;
		
	}
	public static void SendMail(String emailAccount,String receiveMailAccount,String html,String password)
	{
		//1.创建参数配置,用于连接邮箱服务器的参数设置
		Properties props=new Properties();
		//开启debug调试
		props.setProperty("mail.debug", "true");
		//发送服务器需要身份验证
		props.setProperty("mail.smtp.auth", "true");
		//设置邮件服务器主机名
		props.setProperty("mail.host", "smtp.qq.com");
		//发送协议名称
		props.setProperty("mail.transport.protocol", "smtp");
		//2.根据配置创建会话对象，用于和邮件服务器交互
		Session session=Session.getInstance(props);
		//设置debug可以查看详细的发送log
		session.setDebug(true);
		//3.创建一封邮件
		try {
			MimeMessage message=MyUtils.createMimeMessage(session, emailAccount, receiveMailAccount, html);
		//4.根据Session获取邮件传输对象
			Transport transport=session.getTransport();
		//5.使用邮箱账号和密码连接邮箱服务器emailAccount与发件人邮箱一致
			transport.connect(emailAccount,password);
		//6.发送邮件，发送所有收件人地址
			transport.sendMessage(message, message.getAllRecipients());
		//7.关闭连接
			transport.close();
		//8.写入session
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
